package org.ruanjj.multithread.JUC;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

public class ForkJoinDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        MyTask myTask = new MyTask(0,100);

        ForkJoinPool pool = new ForkJoinPool();
        ForkJoinTask<Integer> forkJoinTask = pool.submit(myTask);

        System.out.println(forkJoinTask.get());

        pool.shutdown();
    }
}

class MyTask extends RecursiveTask<Integer>{
    private static final Integer VALUE = 10;

    private int begin;
    private int end;
    private Integer result = 0;

    public MyTask(int begin,int end){
        this.begin = begin;
        this.end = end;
    }
    @Override
    protected Integer compute() {
        if(end - begin <= VALUE){
            for(int i = begin; i<=end; i++){
                result = result+i;
            }
        }else{
            int mid = (end+begin)/2;
            //拆分左
            MyTask task01 = new MyTask(begin,mid);

            //拆分右
            MyTask task02 = new MyTask(mid+1,end);

            task01.fork();
            task02.fork();

            //和并结果
            result = task01.join()+task02.join();
        }
        return result;
    }
}
